package com.duckygo.towerdefense.game.sprites;

import java.util.Arrays;

import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;

import com.duckygo.towerdefense.game.TextureManager;
import com.duckygo.towerdefense.game.scenes.SceneManager;
import com.duckygo.towerdefense.game.scenes.TowerDefenseScene;

public class Terrain2DSprite extends Sprite2D {
	
	public static final int TILE_WIDTH = 32;

	public static final int TILE_HEIGHT = 32;

	
	public static final int MAP_HEIGHT = 20;

	public static final int MAP_WIDTH = 20;

	
	public int[][] map_data = new int[MAP_WIDTH][MAP_HEIGHT];
	
	public Terrain2DSprite(String data) {
		String[] lines = data.split(" ");
		for (int i = 0; i < lines.length; i++) {
			String[] values = lines[i].split(",");
			for (int j = 0; j < values.length; j++) {
				map_data[j][i] = Integer.parseInt(values[j].trim());
			}
		}
	}
	
	@Override
	public void draw(GL10 gl) {

		GL11Ext gl1 = (GL11Ext) gl;
		GL11 gl11 = (GL11)gl;

		TextureManager.lastTexture = -1;
		gl.glBindTexture(GL10.GL_TEXTURE_2D, TextureManager.textures[texture]);

		int crop[] = new int[] { 0, 0, TILE_WIDTH, - TILE_HEIGHT};

		int parent_Y = (int)(SceneManager.HEIGHT - this.y) - TILE_HEIGHT;
		int parent_X = (int)this.x;
		
		for (int x = 0; x < MAP_WIDTH; x ++) {
			for (int y = 0; y < MAP_HEIGHT; y++ ) {
				int tile_id = map_data[x][y];
				
				crop[0] = (int) (Math.floor(tile_id % 16) * TILE_WIDTH) - TILE_WIDTH;
				crop[1] = (int) (Math.floor(tile_id / 16) * TILE_HEIGHT) + TILE_HEIGHT;
				
				gl11.glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, crop, 0);
				gl1.glDrawTexiOES(parent_X + (x * TILE_WIDTH), parent_Y - (y * TILE_HEIGHT), (int)z, TILE_WIDTH, TILE_HEIGHT);
			}
		}
		
	}

	public boolean isWalkable(int x, int y) {
		switch(map_data[x][y]) {
		case 3 * 16 + 6:
		case 4 * 16 + 6:
		case 5 * 16 + 6:
		case 3 * 16 + 7:
		case 4 * 16 + 7:
		case 5 * 16 + 7:
			return true;
		}
		return false;
	}
	

}
